<?php
class Listing_Form_PostAnAddCommercialForm extends Listing_Form_PostAnAddForm
{
    private $_preview_link = '';

    private $_category;
    private $_adid;
    private $_listing;

    protected $elementButtonDecorators = array(
        'ViewHelper',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        );

    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/commercial-post-an-ad.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
    );

    protected $elementSelectDecorators1 = array(
        'ViewHelper',
        array(array('row' => 'HtmlTag'), array('class'=>'select1')),
    );

    protected $elementSelectDecorators2 = array(
        'ViewHelper',
        array('Label', array()),
    );

    public function __construct($options = array())
    {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }
    
    public function init()
    {
        parent::init();

        /*
        $this->addElement('text', 'category0', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'required'   => false,
        ));

        $this->getElement('category0')->setValue((string)$this->_category[0]);

        var_dump((string)$this->_category[0]);
        */
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);
        
        $i = 0;
        foreach($this->_category  as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link'.$i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                    'ViewHelper'
                )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);
        
/*
        $this->addElement('hidden', 'category1', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'value' => (string)$this->_category[0],
            'required'   => false,
        ));
*/
        //$this->getElement('category1')->setValue((string)$this->_category[0]);


        //Title
        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));
		
		//TYPE
        $this->addElement('radio', 'property_type', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),  
            ),
            'multiOptions' => Model_Listing_Commercial::getPropertyTypePostAd(),
            'separator' => '',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));
		
        /**********************************************************
         *                          AGENT
         *********************************************************/
        /*$this->addElement('text', 'agent_name', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        $this->addElement('text', 'agent_phone', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'int',
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'agent_id', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'int',
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'agent_email', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'EmailAddress',
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));/*

        /**********************************************************
         *                          PRICE
         *********************************************************/
        $this->addElement('text', 'sale_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => '仅能填写数字')),
                array('NotEmpty', true, array('messages' => '请填写售价或租价')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*$this->addElement('checkbox', 'price_negotiable', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        /*$this->addElement('hidden', 'add_more_checkbox', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array(array('data' => 'HtmlTag'), array('style' => 'display:none')),
            ),
            'value' => '1',
            'required'   => false,
        ));

        $this->addElement('checkbox', 'sale_lease', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('datePicker', 'lease_enddate', array(
           'jQueryParams' => array(
               'defaultDate' => time(),
               'dateFormat'  => 'dd/mm/yy'
           ),
           'required'   => false,
        ));
        $this->getElement('lease_enddate')->removeDecorator('label');

        $this->addElement('text', 'current_lease_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('checkbox', 'rent_property_too', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        $this->addElement('text', 'rent_price', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => '仅能填写数字')),
                array('NotEmpty', true, array('messages' => '请填写售价或租价')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*$this->addElement('checkbox', 'rent_include_mngt_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));*/

        /**********************************************************
         *                          LOCATION
         *********************************************************/
        $areas = Model_Location::getAreaL1PostAd();
        if (empty($_POST['area_l1'])) {
            $selected_area = 0;
            if (!empty($this->_listing)) {
                $selected_area = '';
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }                   
            }
        }
        else {
            $selected_area = $_POST['area_l1'];
        }
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }        
        $this->addElement('select', 'area_l1', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        //District
        $this->addElement('select', 'area_l2', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => Model_Location::getAreaL2PostAd($selected_area),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        //$this->getElement('area_l2')->setOptions(array('disabled'=>'disabled'));
        
        //location flag
        $this->addElement('radio', 'loc_flag', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'chi' => '中国+香港+澳门',
                'mchi' => '中国大陆',
            ),
            'separator' => '',
            //'value' => '0',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        // Size
        $this->addElement('text', 'size', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        // Tot_Size
        $this->addElement('text', 'total_size', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        /*// Building Age
        $this->addElement('select', 'building_age', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getBuildingAgePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Property Age
        $this->addElement('select', 'property_type', array(
            'validators' => array(
            ),
        'multiOptions' => Model_Listing_Commercial::getPropertyTypePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Floor Zone
        $this->addElement('select', 'floor_zone', array(
            'validators' => array(
            ),
            'multiOptions' => Model_Listing_Commercial::getFloorZonePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));*/

        $this->addElement('textarea', 'cs_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => true,
        ));

        /*$this->addElement('textarea', 'st_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows'=>'',
            'required'   => true,
        ));

        $this->addElement('select', 'location', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                'Alnum',
                array('StringLength', false, 24),
            ),
            'multiOptions' => array(
              1 => '', 'Free', 'Contact'
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Location:',
        ));


        $this->addElement('text', 'street', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));

        $this->addElement('text', 'management_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'government_fee', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        $this->addElement('text', 'other', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // View
        $this->addElement('multiCheckbox', 'views', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getViews(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // FitOutConditions
        $this->addElement('multiCheckbox', 'fitoutconditions', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getFitoutConditions(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Facilities
        $this->addElement('multiCheckbox', 'facilities', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getFitoutConditions(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Toilet
        $this->addElement('multiCheckbox', 'toilet', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getToilet(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Availability
        $this->addElement('multiCheckbox', 'availability', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getAvailability(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Air Conditioning System
        $this->addElement('multiCheckbox', 'airconditioningsystem', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getAirConditioningSystem(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Building Facilities
        $this->addElement('multiCheckbox', 'buildingfacilities', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getBuildingFacilities(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Carparking Facilities
        $this->addElement('multiCheckbox', 'carparkingfacilities', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Commercial::getCarparkingFacilities(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required'   => false,
        ));

        // Number of Stores
        $this->addElement('select', 'numberofstores', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getNumberofStoresPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Ownership
        $this->addElement('select', 'ownership', array(
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getOwnerShipPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Typical Floor Area
        $this->addElement('text', 'typicalfloorarea', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Flooring System
        $this->addElement('select', 'flooringsystem', array(
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getFlooringSystemPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Ceiling Height
        $this->addElement('text', 'ceilingheight', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Number of Passenge Lifts
        $this->addElement('text', 'passengelifts', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Number of Service Lifts
        $this->addElement('text', 'servicelifts', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));

        // Air Conditioning Hours (Monday-Friday)
        $this->addElement('select', 'airconhoursweek', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getHoursPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));

        // Air Conditioning Hours (Saturday)
        $this->addElement('select', 'airconhourssaturday', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => Model_Listing_Commercial::getHoursPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementSelectDecorators2,
            'required'   => false,
        ));*/
        $this->addElement('text', 'st_en', array(
       	 	'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));
        
        $this->addElement('text', 'tag', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Tag:',
        ));
        
        $this->addElement('text', 'remark', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Remark:',
        ));
        
        $this->addElement('text', 'c_name', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Name:',
        ));
        
        $this->addElement('checkbox', 'agent', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'c_tel', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Tel:',
        ));
        
        $this->addElement('text', 'c_msn', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'MSN / QQ:',
        ));
        
        $this->addElement('button', 'validate', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => 'Post your ad',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')))),
        ));

        $this->addElement('button', 'preview', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'button',
            'label'       => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));


        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;

        $this->getDecorator('ViewScript')->setOptions($opt);

    }

    public function populate(array $arr)
    {
        //echo "<PRE>";
        //print_r($this->_listing);
        //exit;
        //
    // Required
        //Title
        // if (empty($arr['title'])) {
            // $this->getElement('title')->setValue($this->_listing->title);
        // }
        //Description
        // if (empty($arr['description'])) {
            // $this->getElement('description')->setValue($this->_listing->description);
        // }
		
		if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
			
            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
			$this->getElement('cs_en')->setValue($this->_listing->cs_en);
			$this->getElement('st_en')->setValue((string)$this->_listing->st_en);
			
			
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
			
			$this->getElement('tl_en')->setValue($this->_listing->tl_sc);
            $this->getElement('cs_en')->setValue($this->_listing->cs_sc);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_sc);
			
		}
		
        //Price
        if(empty($arr['price'])) {
            if (!empty($this->_listing->sale_price)) {
                $this->getElement('sale_price')->setValue($this->_listing->sale_price);
            }
            if (!empty($this->_listing->rent_price)) {
                $this->getElement('rent_price')->setValue($this->_listing->rent_price);
            }
        }
        //Area
        if (empty($arr['area_l1'])) {
                $selected_area = '';
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }            
            $this->getElement('area_l1')->setValue((string)$selected_area);
        }
        //District
        if (empty($arr['area_l2'])) {
            if (isset($this->_listing->area_l2->_id)) {
                $this->getElement('area_l2')->setValue((string)$this->_listing->area_l2->_id);
            }
        }
        //Street
        // if (empty($arr['street'])) {
            // $this->getElement('address')->setValue((string)$this->_listing->street);
        // }
        //Price Negotiable
        /*if (empty($arr['price_negotiable'])) {
            $this->getElement('price_negotiable')->setValue((string)$this->_listing->price_negotiable);
        }
        //Sell with lease
        if (empty($arr['sale_lease'])) {
            $this->getElement('sale_lease')->setValue((string)$this->_listing->sale_lease);
            if ($this->_listing->sale_lease == 1) {
                //Current lease
                if (empty($arr['current_lease_price'])) {
                    $this->getElement('current_lease_price')->setValue((string)$this->_listing->current_lease_price);
                }
                //Lease End Date
                if (empty($arr['lease_enddate'])) {
                    $this->getElement('lease_enddate')->setValue((string)$this->_listing->lease_enddate);
                }
            }
        }*/
        //Rent my Property too
        if (!empty($this->_listing->rent_price)) {
            //Rent Price
            if (empty($arr['rent_price'])) {
                $this->getElement('rent_price')->setValue((string)$this->_listing->rent_price);
            }
            /*/Rent Price
            if (empty($arr['rent_include_mngt_fee'])) {
                $this->getElement('rent_include_mngt_fee')->setValue((string)$this->_listing->rent_include_mngt_fee);
            }*/
        }
        
        //Size
        if (empty($arr['size'])) {
            $this->getElement('size')->setValue((string)$this->_listing->size);
        }
		
		//Total Size
        if (empty($arr['total_size'])) {
            $this->getElement('total_size')->setValue((string)$this->_listing->total_size);
        }
        //agent
        if (empty($arr['agent'])) {
            $this->getElement('agent')->setValue((string)$this->_listing->agent);
        }
   		 if (empty($arr['property_type'])) {
            $this->getElement('property_type')->setValue((string)$this->_listing->property_type);
        }
    /*/Optional
        //Property Type
        if (empty($arr['property_type'])) {
            $this->getElement('property_type')->setValue((string)$this->_listing->property_type);
        }
        //Building Age
        if (empty($arr['building_age'])) {
            $this->getElement('building_age')->setValue((string)$this->_listing->building_age);
        }
        //Floor Zone
        if (empty($arr['floor_zone'])) {
            $this->getElement('floor_zone')->setValue((string)$this->_listing->floor_zone);
        }
        //Fit-Out Conditions
        if (empty($arr['fitoutconditions'])) {
            $this->getElement('fitoutconditions')->setValue((array)$this->_listing->fitoutconditions);
        }
        //View
        if (empty($arr['views'])) {
            $this->getElement('views')->setValue((array)$this->_listing->views);
        }
        //Availability
        if (empty($arr['availability'])) {
            $this->getElement('availability')->setValue((array)$this->_listing->availability);
        }       
        //Toilet
        if (empty($arr['toilet'])) {
            $this->getElement('toilet')->setValue((array)$this->_listing->toilet);
        }
        //Conditions
        if (empty($arr['airconditioningsystem'])) {
            $this->getElement('airconditioningsystem')->setValue((array)$this->_listing->airconditioningsystem);
        }
        //Management Fee
        if (empty($arr['management_fee'])) {
            $this->getElement('management_fee')->setValue((string)$this->_listing->management_fee);
        }
        //government Fee
        if (empty($arr['government_fee'])) {
            $this->getElement('government_fee')->setValue((string)$this->_listing->government_fee);
        }
        //Building Facilities
        if (empty($arr['buildingfacilities'])) {
            $this->getElement('buildingfacilities')->setValue((array)$this->_listing->buildingfacilities);
        }
        //Carparking Facilities
        if (empty($arr['carparkingfacilities'])) {
            $this->getElement('carparkingfacilities')->setValue((array)$this->_listing->carparkingfacilities);
        }
        //Typical Floor Area
        if (empty($arr['typicalfloorarea'])) {
            $this->getElement('typicalfloorarea')->setValue((string)$this->_listing->typicalfloorarea);
        }
        //Ceiling Height
        if (empty($arr['ceilingheight'])) {
            $this->getElement('ceilingheight')->setValue((string)$this->_listing->ceilingheight);
        }
        //Passenge Lifts
        if (empty($arr['passengelifts'])) {
            $this->getElement('passengelifts')->setValue((string)$this->_listing->passengelifts);
        }
        //Service Lifts
        if (empty($arr['servicelifts'])) {
            $this->getElement('servicelifts')->setValue((string)$this->_listing->servicelifts);
        }
        //Number of Stores
        if (empty($arr['numberofstores'])) {
            $this->getElement('numberofstores')->setValue((array)$this->_listing->numberofstores);
        }
        //Flooring System
        if (empty($arr['flooringsystem'])) {
            $this->getElement('flooringsystem')->setValue((array)$this->_listing->flooringsystem);
        }
        //Air Conditioning Hours Week
        if (empty($arr['airconhoursweek'])) {
            $this->getElement('airconhoursweek')->setValue((array)$this->_listing->airconhoursweek);
        }
        //Air Conditioning Hours Saturday
        if (empty($arr['airconhourssaturday'])) {
            $this->getElement('airconhourssaturday')->setValue((array)$this->_listing->airconhourssaturday);
        }
        //Ownership
        if (empty($arr['ownership'])) {
            $this->getElement('ownership')->setValue((array)$this->_listing->ownership);
        }*/
		if (empty($arr['tag'])) {
        	if(!empty($this->_listing->tags)){
				$this->getElement('tag')->setValue(implode(',', $this->_listing->tags));
			}            
        }
        
        if (empty($arr['remark'])) {
            $this->getElement('remark')->setValue((string)$this->_listing->remark);
        }
        
        if (empty($arr['c_name'])) {
            $this->getElement('c_name')->setValue((string)$this->_listing->c_name);
        }
        
        if (empty($arr['c_tel'])) {
            $this->getElement('c_tel')->setValue((string)$this->_listing->c_tel);
        }
        
        if (empty($arr['c_msn'])) {
            $this->getElement('c_msn')->setValue((string)$this->_listing->c_msn);
        }
        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false)
    {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if(empty($ad->us)) {
                    $ad->user        = $user->_id;    
                }
            } else {
                $ad->user        = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }
        $POST = $_POST;
        
        //Requiered Attributs
        // $ad->title                  = $POST['title'];
        // $ad->description            = $POST['description'];
		
		$classname = Model_Listing::getInstanceClassname((array)$this->_listing->ca);
		$translateFields = $classname::getTranslationFormField();
		
		$this->translate($ad, $translateFields, $classname);
		
		/* $gt = new Ac_Translation();
		$gt2 = new Ac_Translation();
		$gt3 = new Ac_Translation();
		
		if (Zend_Registry::get('current_language') == 'en'){
			$ad->ad_type = 1;
			$ft = 'en';
			$tt = 'zh-TW';
			$ad->title_en       = $POST['title'];
			$ad->description_en = $POST['description'];
			$ad->street     = $POST['address'];
			
			if (empty($ad->title_tc)) 
			$ad->title_tc = $gt->translate($POST['title'], $tt, $ft);
				
			if (empty($ad->description_tc))
			$ad->description_tc = $gt2->translate($POST['description'], $tt, $ft);
			
			if (empty($ad->street_tc))
			$ad->street_tc     = $gt3->translate($POST['address'], $tt, $ft);

		} else {
			$ad->ad_type = 2;
			$ft = 'zh-TW';
			$tt = 'en';		
			$ad->title_tc       = $POST['title'];
			$ad->description_tc = $POST['description'];
			$ad->street_tc     = $POST['address'];
			
			if (empty($ad->title_en))
			$ad->title_en = $gt->translate($POST['title'], $tt, $ft);
			
			if (empty($ad->description_en))
			$ad->description_en = $gt2->translate($POST['description'], $tt, $ft);
			
			if (empty($ad->street))
			$ad->street    = $gt3->translate($POST['address'], $tt, $ft);

		} */
		
        //Temporary
          $whole        = false;
          $office       = false;
          $shop         = false;
          $warehouse    = false;
          while (list($k, $cat) = each($this->_category)) {
            //Whole Buildings
            if (($cat->nm_en == "Whole Buildings for Sale") || ($cat->nm_en == "Whole Buildings for Rent")) {
                if ($whole) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Whole Buildings';
                $whole = true;
            }
            //Offices
            if (($cat->nm_en == "Offices for Sale") || ($cat->nm_en == "Offices for Rent")) {
                if ($office) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Offices';
                $office = true;
            }
            //Shops
            if (($cat->nm_en == "Shops for Sale") || ($cat->nm_en == "Shops for Rent")) {
                if ($shop) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Shops';
                $shop     = true;
            }
            //Warehouses
            if (($cat->nm_en == "Warehouses for Sale") || ($cat->nm_en == "Warehouses for Rent")) {
                if ($warehouse) {
                    unset($this->_category[$k]);
                    continue;
                }
                $this->_category[$k]->nm_en = 'Warehouses';
                $warehouse     = true;
            }
        }

        //
        //Ce qu'il faut faire : Lier les level 3 for sale et for rent avec le level 3 de meme niveau
        //

        //Save the category related to this Ad
        $ad->ca = array();
        foreach($this->_category as $cat) {
            //Whole Buildings
            if ($cat->nm_en == 'Whole Buildings') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c558'));
                $rent = Model_Category::one(array('id' => 'c557'));
                if ((!empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'] )) & (empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($rent->_id);
                }
            }
            //Offices
            elseif ($cat->nm_en == 'Offices') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c552'));
                $rent = Model_Category::one(array('id' => 'c551'));
                if ((!empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'] )) & (empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($rent->_id);
                }
            }
            //Shops
            elseif ($cat->nm_en == 'Shops') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c440'));
                $rent = Model_Category::one(array('id' => 'c442'));
                if ((!empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'] )) & (empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($rent->_id);
                }
            }
            //Warehouses
            elseif ($cat->nm_en == 'Warehouses') {
                //For Sale and Rent
                $sale = Model_Category::one(array('id' => 'c573'));
                $rent = Model_Category::one(array('id' => 'c572'));
                if ((!empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                    $ad->addCategory($rent->_id);
                }
                //For Sale
                if ((!empty($POST['sale_price'] )) & (empty($POST['rent_price'] ))) {
                    $ad->addCategory($sale->_id);
                }
                //For Rent
                if ((empty($POST['sale_price'] )) & (!empty($POST['rent_price'] ))) {
                    $ad->addCategory($rent->_id);
                }
            }
            else
            {
                $ad->addCategory($cat->_id);
            }
        }
        
        // If it is a sale
        if (!empty($POST['sale_price'] )) {
            $ad->sale_price             = $POST['sale_price'];
            //$ad->salepricepersqft       = (int)((int)$POST['sale_price']/(int)$POST['size']);
            //$ad->salepricetotal         = (int)$POST['management_fee']+(int)$POST['government_fee']+(int)$POST['sale_price'];
            //$ad->price_negotiable       = (int)$POST['price_negotiable'];
            //If there is a lease
            /*if ($POST['sale_lease'] == '1') {
                $ad->sale_lease             = $POST['sale_lease'];
                $ad->lease_enddate          = $POST['lease_enddate'];
                $ad->current_lease_price    = $POST['current_lease_price'];
            }
            else {
                $ad->sale_lease             = '';
                $ad->lease_enddate          = '';
                $ad->current_lease_price    = '';
            }*/
        }
        else {
            $ad->sale_price             = '';
        }

        // If it is a rent
        if (!empty($POST['rent_price'])) {
            //$ad->rent_include_mngt_fee  = $POST['rent_include_mngt_fee'];
            $ad->rent_price             = $POST['rent_price'];
            /*$ad->rentpricepersqft       = (int)((int)$POST['rent_price']/(int)$POST['size']);
            if ($POST['rent_include_mngt_fee'] == '1') {
                $ad->rentpricetotal         = $POST['rent_price'];
            }
            else {
                $ad->rentpricetotal         = (int)$POST['management_fee']+(int)$POST['government_fee']+(int)$POST['rent_price'];
            }*/
        }
        else {
            //$ad->rent_include_mngt_fee  = '';
            $ad->rent_price             = '';
        }

        //$ad->street                 = $POST['address'];
        $ad->size                   = $POST['size'];        
        $ad->area_l1                = new MongoId($POST['area_l1']);
        if ((string)$_POST['area_l1'] == ONLINE_ONLY_AREA) {
            $ad->area_l2 = new MongoId(ONLINE_ONLY_AREA);
        }
        elseif((string)$this->getValue('area_l1') == ENTIRE_CITY) {
            $ad->area_l2 = new MongoId(ENTIRE_CITY);
        }
        else {
            $ad->area_l2 = new MongoId($_POST['area_l2']);
        }

        /*/Optional Attributs
        if (!empty($POST['building_age']))          {$ad->building_age          = $POST['building_age'];}
        if (!empty($POST['property_type']))         {$ad->property_type         = $POST['property_type'];}
        if (!empty($POST['floor_zone']))            {$ad->floor_zone            = $POST['floor_zone'];}

        if (!empty($POST['fitoutconditions']))      {$ad->fitoutconditions      = $POST['fitoutconditions'];}
        if (!empty($POST['views']))                 {$ad->views                 = $POST['views'];}
        if (!empty($POST['availability']))          {$ad->availability          = $POST['availability'];}
        if (!empty($POST['airconsystem']))          {$ad->airconsystem          = $POST['airconsystem'];}
        if (!empty($POST['toilet']))                {$ad->toilet                = $POST['toilet'];}
        if (!empty($POST['management_fee']))         {$ad->management_fee         = $POST['management_fee'];}
        if (!empty($POST['government_fee']))        {$ad->government_fee        = $POST['government_fee'];}

        if (!empty($POST['building_facilities']))   {$ad->building_facilities   = $POST['building_facilities'];}
        if (!empty($POST['carparkingfacilities']))  {$ad->carparkingfacilities  = $POST['carparkingfacilities'];}
        if (!empty($POST['typicalfloorarea']))      {$ad->typicalfloorarea      = $POST['typicalfloorarea'];}
        if (!empty($POST['ceilingheight']))         {$ad->ceilingheight         = $POST['ceilingheight'];}
        if (!empty($POST['passengelifts']))         {$ad->passengelifts         = $POST['passengelifts'];}
        if (!empty($POST['servicelifts']))          {$ad->servicelifts          = $POST['servicelifts'];}
        if (!empty($POST['numberstores']))          {$ad->numberstores          = $POST['numberstores'];}
        if (!empty($POST['flooringsystem']))        {$ad->flooringsystem        = $POST['flooringsystem'];}
        if (!empty($POST['airconhoursweek']))       {$ad->airconhoursweek       = $POST['airconhoursweek'];}
        if (!empty($POST['airconhourssaturday']))   {$ad->airconhourssaturday   = $POST['airconhourssaturday'];}
        if (!empty($POST['ownership']))             {$ad->ownership             = $POST['ownership'];}*/
        $ad->tl_sc 			= (string)$this->getValue('tl_en');
        $ad->cs_sc 			= (string)$this->getValue('cs_en');
        $ad->st_sc 			= (string)$this->getValue('st_en');
 		if (!empty($POST['tag']))         {$ad->tags         = array_values(explode(',',$POST['tag']));}
        $ad->rmrk 			= (string)$this->getValue('remark');
        $ad->c_name 		= (string)$this->getValue('c_name');
        $ad->c_tel 			= (string)$this->getValue('c_tel');
        $ad->c_msn 			= (string)$this->getValue('c_msn');
        $ad->loc_flag = (string)$this->getValue('loc_flag');
        $ad->total_size 	= $POST['total_size'];
        $ad->property_type 	= $POST['property_type'];
        $ad->agent = (string)$this->getValue('agent');
        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->forceSave();
        }
        return $ad;
    }

    protected function continueFillup()
    {

    }

    public function __toString()
    {
        $str = '
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                         //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';
		
		$str2 = '
			$j("tl_tc_back").click(function(event) {
			alert("test");
   
			});
		
		';
        $this->view->JQuery()->addJavascript($str);
		$this->view->JQuery()->addJavascript($str2);
        return parent::__toString();
    }

    public function isValid($post = array())
    {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if (Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('Your Ad contains banned words');
            $test2 = false;
        }

        //Check Bad Words in Description
        if (Ac_Util::checkBadWord($_POST['cs_en'])) {
            $this->getElement('cs_en')->addError('Your Ad contains banned words');
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }

        //Empty field for lease or rent if not checked
        if (empty($_POST['rent_price']) && empty($_POST['sale_price'])) {
            $this->getElement('rent_price')->addError('请填写售价或租价');
            $this->getElement('sale_price')->addError('请填写售价或租价');
            $test2 = false;
        }
        else {
            $this->getElement('rent_price')->setValue($_POST['rent_price']);
            $this->getElement('sale_price')->setValue($_POST['sale_price']);
        }
        /*if ($post['sale_lease'] == '0') {
            $this->getElement('current_lease_price')->setValue('');
            $this->getElement('lease_enddate')->setValue('');
        }*/

        //For Sale
    
        /*if (empty($_POST['sale_price'])){
            $this->getElement('sale_price')->addError('请填写售价或租价');
            $test2 = false;
        }            
        else {
            $this->getElement('sale_price')->setValue($_POST['sale_price']);
        }*/

        /*/For Sale with a lease
        if (($post['sale_lease'] == '1') & (empty($post['sale_price']))) {
            $this->getElement('sale_price')->addError('This information is required');
            $test2 = false;
        }
        if ($post['sale_lease'] == '1') {
            if (empty($post['current_lease_price'])) {
                $this->getElement('current_lease_price')->addError('This information is required');
                $test2 = false;
            }
            if (empty($post['lease_enddate'])) {
                $this->getElement('lease_enddate')->addError('This information is required');
                $test2 = false;
            }
        }*/
        
        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($_POST['area_l1'])));
        if (!empty($data)) {
            /*if ($data->nm_en != 'Online Only') {
                if (empty($post['district'])) {
                    $this->getElement('district')->addError('This information is required');
                    $test2 = false;
                }
            }*/
            if ($data->nm_sc != 'Entire City') {
                if (empty($post['area_l2'])) {
                    $this->getElement('area_l2')->addError('This information is required');
                    $test2 = false;
                }
            }
        }

        //echo "<PRE>";
        //var_dump($this->getErrors());exit;

        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }     
    }
}
